package com.yachang.qym.usbhost.service;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

import com.yachang.qym.usbhost.utils.NetConnected;
import com.yachang.qym.usbhost.utils.NotificationCenter;

public class CheckNetService extends Service {

    private static int NET_RUNNING = 1;

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what == 1){
                NotificationCenter.getInstance().postNotification("ReopenApp");
                CheckNetService.this.stopSelf();
            }
        }
    };
    public CheckNetService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        handler.postDelayed(runnable, 1000);
        return super.onStartCommand(intent, flags, startId);
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (NetConnected.isConnectNet(getApplicationContext())) {
                Message message = new Message();
                message.what = NET_RUNNING;
                handler.sendMessage(message);
            } else {
                handler.postDelayed(runnable, 1000);
            }
        }
    };
}
